/*
 * File:   MergeMdiChild.cpp
 * Author: Morpheus
 *
 * Created on 20 juin 2013, 17:21
 */

#include "MergeMdiChild.h"
#include "MyBatchUnitModel.h"

#include <QtGui/qtextcursor.h>
#include <QtCore/qfileinfo.h>
#include <QtCore/qbytearray.h>
#include <QtCore/qiodevice.h>
#include <QtGui/QCloseEvent>
#include <QtWidgets/qmessagebox.h>
#include <QtGui/qtextdocumentwriter.h>
#include <QtGui/qimagewriter.h>

MergeMdiChild::MergeMdiChild(QWidget* parent)
 : QWidget(parent) {
    widget.setupUi(this);
    setAttribute(Qt::WA_DeleteOnClose);
    
    QStringList listSupport;
    listSupport << tr("PDF") << tr("SVG") << tr("PS");
    foreach(QByteArray supported, QTextDocumentWriter::supportedDocumentFormats()){
        listSupport << QString::fromLatin1(supported).toUpper();
    }
    foreach(QByteArray supported, QImageWriter::supportedImageFormats()){
        listSupport << QString::fromLatin1(supported).toUpper();
    }
    widget.comboBoxFmt->addItems(listSupport);
    
    MyBatchUnitModel* model = new MyBatchUnitModel(this);
    widget.tableView->setModel(model);
    
    connect(model, SIGNAL(saveFile(QString, bool)), this, SLOT(setSaveFile(QString, bool)) );
    connect(model, SIGNAL(modified(bool)), this, SLOT(modified(bool)) );
    connect(widget.lineEditName, SIGNAL(textChanged(QString)), model, SLOT(setName(QString)) );
    connect(widget.lineEditSaveFilePatern, SIGNAL(textChanged(QString)), model, SLOT(setSaveFilePatern(QString)) );
    connect(widget.comboBoxFmt, SIGNAL(currentIndexChanged(QString)), model, SLOT(setSaveFileFormat(QString)) );

    connect(widget.tableView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex, QModelIndex)), this, SLOT(OnTableViewCurrentRowChanged(QModelIndex, QModelIndex)) );
    OnTableViewCurrentRowChanged(QModelIndex(), QModelIndex());
}

MergeMdiChild::~MergeMdiChild() {
}

void MergeMdiChild::closeEvent(QCloseEvent* event){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    if(model->isModified()){
        int res = QMessageBox::question(this, trUtf8("%1 - Sauvegarder ?").arg(m_currTitle), trUtf8("Le Batch %1 à été modifié.\n Souhaitez vous le Sauvegarder").arg(m_currTitle), QMessageBox::Yes | QMessageBox::No | QMessageBox::Abort, QMessageBox::Yes);
        if(res == QMessageBox::Abort){
            event->ignore();
            return;
        }
        if(res == QMessageBox::Yes){
            on_pushButtonSave_clicked();
        }
    }
    
    event->accept();
}

MyBatchMerge MergeMdiChild::getBatchMerge() const {
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    return model->getBatchMerge();
}

void MergeMdiChild::setBatchMerge(const MyBatchMerge& data) {
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    setUpdatesEnabled(false);
    
    model->setBatchMerge(data);
    widget.lineEditName->setText(data.getName());
    widget.lineEditSaveFilePatern->setText(data.getSaveFilePatern());
    widget.comboBoxFmt->setCurrentText(data.getSaveFileFormat());
    m_currTitle = data.getName();
    setSaveFile(data.getSaveFile(), data.isSaveFileOk());
    setUpdatesEnabled(true);
    model->setModified(false);
    modified(false);
}

int MergeMdiChild::getUuid() const{
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    return model->getBatchMerge().getUUID();
}

void MergeMdiChild::setSaveFile(const QString& v, const bool& b){
    if(!v.isEmpty()){
        QFileInfo infoFile(v);
        widget.lineEdit->setText(infoFile.absoluteFilePath());
    }else{
        widget.lineEdit->clear();
    }
    
    if(!b || v.isEmpty()){
        widget.lineEdit->setStyleSheet(QString("background-color: rgb(255, 0, 0);"));
    }else{
        widget.lineEdit->setStyleSheet(QString(""));
    }
}
void MergeMdiChild::on_tableView_activated(const QModelIndex& index){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    MyBatchUnit unit;
    if(index.isValid()){
        widget.widget_2->setVisible(true);
        unit = model->getBatchUnit(index);
    }
    if(model->getBatchMerge().getBatchList().contains(m_currUnit)){
        model->insertBatchUnit(-1, m_currUnit);
    }
    m_currUnit = unit;
    unit = MyBatchUnit();
    if(model->getBatchMerge().getBatchList().contains(m_currUnit)){
        if(!m_currUnit.isFile()){
            widget.groupBoxTagBatchUnit->setVisible(true);
            widget.textEditOutline->setVisible(true);
            widget.textEdit->setReadOnly(false);
        }else{
            widget.groupBoxTagBatchUnit->setVisible(false);
            widget.textEditOutline->setVisible(false);
            widget.textEdit->setReadOnly(true);
        }
        QApplication::setOverrideCursor(QCursor(Qt::BusyCursor));
        QTextDocument* doc = m_currUnit.document();
        qSwap(m_currUnit, unit);
        widget.textEdit->setDocument(doc);
        qSwap(m_currUnit, unit);
        if(!m_currUnit.isFile()){
            bool bOk = true;
            QString outLine = model->getBatchMerge().interpretPatern(widget.textEdit->toPlainText(), bOk);
            updateTextOutline(outLine, bOk);
        }
        QApplication::restoreOverrideCursor();
    }else{
        widget.widget_2->setVisible(false);
    }
    model->setCurrUnit(m_currUnit.getUUID());
}
void MergeMdiChild::OnTableViewCurrentRowChanged(const QModelIndex& curr, const QModelIndex& /*previous*/){
    if(curr.isValid()){
        MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
        widget.toolButtonGoDown->setEnabled(curr.row() < model->rowCount()-1);
        widget.toolButtonGoUp->setEnabled(curr.row() > 0);
        widget.toolButtonAdd->setEnabled(true);
        widget.toolButtonDel->setEnabled(true);
    }else{
        widget.toolButtonAdd->setEnabled(false);
        widget.toolButtonDel->setEnabled(false);
        widget.toolButtonGoUp->setEnabled(false);
        widget.toolButtonGoDown->setEnabled(false);
        widget.widget_2->setVisible(false);
    }
}
void MergeMdiChild::on_toolButtonAdd_clicked(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    QModelIndex idx = widget.tableView->currentIndex();
    model->insertBatchUnit(idx.row(), MyBatchUnit());
}
void MergeMdiChild::on_toolButtonDel_clicked(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    QModelIndex idx = widget.tableView->currentIndex();
    model->removeBatchUnit(idx);
}
void MergeMdiChild::on_toolButtonGoUp_clicked(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    QModelIndex idx = widget.tableView->currentIndex();
    if(model->goUpBatchUnit(idx)){
        widget.tableView->selectRow(idx.row()-1);
    }
}
void MergeMdiChild::on_toolButtonGoDown_clicked(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    QModelIndex idx = widget.tableView->currentIndex();
    if(model->goDownBatchUnit(idx)){
        widget.tableView->selectRow(idx.row()+1);
    }
}
void MergeMdiChild::on_pushButtonSave_clicked(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    if(!model->isModified())
        return;

    foreach(MyBatchUnit unit, model->getBatchMerge().getBatchList()){
        unit.save();
    }
    model->setModified(false);
    model->setDoWithSuccess(false);

    QByteArray array;
    {
        QDataStream out(&array, QIODevice::WriteOnly);
        out << model->getBatchMerge();
    }
    
    emit savedBatch(array);
}
void MergeMdiChild::on_pushButtonCancel_clicked(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    model->setModified(false);
    parentWidget()->close();
}
void MergeMdiChild::on_textEdit_textChanged(){
    MyBatchUnitModel* model = qobject_cast<MyBatchUnitModel*>(widget.tableView->model());
    int idx = model->getBatchMerge().getBatchList().indexOf(m_currUnit);
    if(idx != -1){
        modified(true);
        widget.tableView->update(model->index(idx, 0));
        if(!m_currUnit.isFile()){
            bool bOk = true;
            QString outLine = model->getBatchMerge().interpretPatern(widget.textEdit->toPlainText(), bOk);
            updateTextOutline(outLine, bOk);
        }
    }
}

void MergeMdiChild::updateTextOutline(const QString& s, const bool& b){
    widget.textEditOutline->setPlainText(s);
    if(b){
        widget.textEditOutline->setStyleSheet(QString(""));
    }else{
        widget.textEditOutline->setStyleSheet(QString("background-color: rgb(255, 0, 0);"));
    }
}

void MergeMdiChild::modified(const bool& b){
    setWindowTitle( QString("%1%2").arg(m_currTitle).arg(b? tr(" *") : tr("") ) );
}

void MergeMdiChild::on_tagWidgetSaveFile_formTag(const QString& s){
    widget.lineEditSaveFilePatern->setFocus();
    widget.lineEditSaveFilePatern->insert(s);
}
void MergeMdiChild::on_tagWidgetBatchUnit_formTag(const QString& s){
    widget.textEdit->setFocus();
    QTextCursor tcursor(widget.textEdit->document());
    tcursor.insertText(s);
}
